#include "tcpdialog.h"
#include "ui_tcpdialog.h"

#include <QTextStream>
#include <QDateTime>

#include <QNetworkInterface>
#include <QHostAddress>


constexpr quint16 port = 5000;

TCPDialog::TCPDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TCPDialog)
{
    ui->setupUi(this);
    this->setWindowTitle(tr("TCP服务器模板"));

    // 初始化TCP
    initTcpServer();
}

TCPDialog::~TCPDialog()
{
    delete ui;
}

// 获取内网IP的代码
QString TCPDialog::getLocalIpAddress() {
    QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
    for (int i = 0; i < ipAddressesList.size(); ++i) {
        if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
            ipAddressesList.at(i).toIPv4Address()) {
            return ipAddressesList.at(i).toString();
        }
    }
    return "192.168.1.100"; // 默认值
}

void TCPDialog::initTcpServer()
{
    // TCP服务器对象
    m_server = new TcpServer();

    QObject::connect(m_server, &TcpServer::clientConnected, [&](qintptr descriptor, const QString &info) {
        m_descriptorClient = descriptor;
        ui->textBrowser_log->append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                                    + " - Client connected: [descriptor:" + QString::number(descriptor,16).toUpper() + "] - " + info);
    });

    QObject::connect(m_server, &TcpServer::clientDisconnected, [&](qintptr descriptor) {
        m_descriptorClient = descriptor;
        ui->textBrowser_log->append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                                    + "- Client disconnected: [descriptor:" + QString::number(descriptor,16).toUpper() + "]");
    });

    QObject::connect(m_server, &TcpServer::messageReceived, [&](qintptr descriptor, const QString &message) {
        m_descriptorClient = descriptor;
        ui->textEdit_recv->append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                                  + " - Message from [descriptor:" + QString::number(descriptor,16).toUpper() + "]" + ": " + message);
    });

    QObject::connect(m_server, &TcpServer::serverError, [&](const QString &error) {
        ui->textBrowser_log->append(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                                    + " - Server error: " + error);
    });

    QString ip = getLocalIpAddress();
    if (!m_server->startServer(QHostAddress(ip), port)) {
        qCritical("开启TCP服务器失败\n");
    }
}

// 发送到客户端
void TCPDialog::on_PB_send_clicked()
{
    QString send = ui->textEdit_send->toPlainText();
    m_server->sendToClient(m_descriptorClient, send);
}

// 广播给所有客户端
void TCPDialog::on_PB_sendBroadcast_clicked()
{
    m_server->broadcastMessage("I am a server");
}
